<template>
    <div>
        <div class="header block">
            <div class="header-left">
                <img :src="tioInfo.insurCompanyLogo" alt="" class="portrait" />
                <div class="header-left-info">
                    <div class="left-info-title">
                        <div>
                            {{ tioInfo.insurCompanyPlanName }}
                        </div>
                        <div class="info-title-tips" v-if="tioInfo.type === 4">
                            月单
                        </div>
                        <!-- <div class="info-title-month">
                <el-date-picker
                    v-model="timeMonth"
                    type="month"
                    format="YYYY-MM"
                    value-format="YYYY-MM"
                    placeholder="请选择月份"
                    style="width:130px"
                    @click="()=>{return}"
                    size="small"
                >
                </el-date-picker>
            </div> -->
                    </div>
                    <div class="left-info-date">
                        {{ tioInfo.beginTime }} 至
                        {{ tioInfo.endTime || '暂无到期时间' }}
                    </div>
                </div>
            </div>
            <div class="header-right flex flex-ai-c flex-wrap">
                <button v-if="canInsureRenewal && !tioInfo.isEnd" class="btn btn-white-blue right-btn" @click="onRenew">
                    <!-- <el-icon><plus /></el-icon> -->
                    <!-- <i class="el-icon el-icon-plus" /> -->
                    <img class="header-right-img" src="../assets/long-insure/renewal.png" />
                    续保
                </button>
                <button v-if="!tioInfo.isEnd" class="btn btn-green right-btn" @click="onInsureAdd">
                    <!-- <el-icon><plus /></el-icon> -->
                    <!-- <i class="el-icon el-icon-plus" /> -->
                    <img class="header-right-img" src="../assets/long-insure/add-btn.png" />
                    加保
                </button>
                <button v-if="!tioInfo.isEnd" class="btn btn-red right-btn" @click="onInsureSubtract">
                    <!-- <i class="el-icon el-icon-minus" /> -->
                    <img class="header-right-img" src="../assets/long-insure/reduce-btn.png" />
                    减保
                </button>

                <export-button class="mg-l-20" @export="handleExport"></export-button>
                <!--        <button-->
                <!--          class="btn btn-red right-btn"-->
                <!--          style="background:#1989FA"-->
                <!--          @click="handleExport"-->
                <!--        >-->
                <!--          <i class="el-icon el-icon-upload2"/>-->
                <!--          导出-->
                <!--        </button>-->
            </div>
        </div>
        <div class="container-info-box">
            <div class="row container-row-box">
                <div class="block-title">客户管理</div>
                <div>
                    <el-date-picker v-model="customerDate" type="month" placeholder="选择日期" @change="getInsureDetailInfo"
                        format="YYYY/MM" value-format="YYYY-MM" />
                </div>
            </div>
            <div class="block-active-list">
                <div class="block block-active">
                    <div class="block-header">
                        <div class="block-title">总人数</div>
                        <div class="block-more">
                            <!-- <div class="">查看详情</div>
              <div class="triangle"></div> -->
                        </div>
                    </div>
                    <div class="block-content ">
                        <div class="row">
                            <div class="">
                                <div class="key">人数</div>
                                <div class="balance">
                                    <span class="number">{{
                                        tioInfo.insurTotalCount
                                    }}</span>
                                </div>
                            </div>
                            <img class="img-chart" src="../assets/chart/chart-line-green.png" />
                        </div>
                    </div>
                </div>
                <div class="block block-active">
                    <div class="block-header">
                        <div class="block-title">当前在保人数</div>
                        <div class="block-more">
                            <!-- <div class="">查看详情</div>
              <div class="triangle"></div> -->
                        </div>
                    </div>
                    <div class="block-content">
                        <div class="row">
                            <div class="">
                                <div class="key">人数</div>
                                <div class="number">
                                    {{ tioInfo.insurValidCount }}
                                </div>
                            </div>
                            <img class="img-chart" src="@/assets/chart/chart-line-blue.png" />
                        </div>
                    </div>
                </div>
                <div class="block block-active">
                    <div class="block-header">
                        <div class="block-title">本月保费</div>
                        <div class="block-more">
                            <!-- <div class="">查看详情</div>
              <div class="triangle"></div> -->
                        </div>
                    </div>
                    <div class="block-content">
                        <div class="row">
                            <div class="">
                                <div class="key">金额（元）</div>
                                ¥<span class="number">{{
                                    tioInfo.monthAmount
                                    }}</span>
                            </div>
                            <img class="img-chart" src="../assets/chart/chart-bar-blue.png" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container-list">
            <div class="block premium-trend">
                <div class="block-header">
                    <div class="block-title">加减记录</div>
                    <div>
                        <el-date-picker v-model="countDate" type="date" placeholder="选择日期"
                            @change="getInsureDetailAdditionList" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                    </div>
                </div>
                <div class="block-content">
                    <div class="table">
                        <!-- @selection-change="handleSelectionChange" -->
                        <el-table :data="countList" style="width: 100%" :header-row-style="{ color: '#202536' }"
                            :row-style="{ color: '#5E617D' }" :header-cell-style="{ background: '#F7F8FC' }">
                            <!-- <el-table-column type="index" label="序号" /> -->
                            <el-table-column label="操作类型">
                                <template #default="scope">
                                    <div :class="[
                                        'operation-type-box',
                                        scope.row.operationType == 1 || scope.row.operationType == 2
                                            ? 'operation-type-box-active'
                                            : ''
                                    ]">
                                        <img v-if="scope.row.operationType == 0" class="operation-type-img"
                                            src="../assets/long-insure/add-safe.png" />
                                        <img v-if="scope.row.operationType == 1 || scope.row.operationType == 2"
                                            class="operation-type-img" src="../assets/long-insure/reduce-safe.png" />
                                        {{
                                            scope.row.operationType == 1 ? '减保' : scope.row.operationType == 2 ? '撤保' : '加保'
                                        }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="人数" prop="total"></el-table-column>
                            <el-table-column label="生效日期" prop="insurStartDate"></el-table-column>
                            <el-table-column width="200px" prop="createTime" label="录入时间" />
                            <el-table-column label="录入人" prop="managerName"></el-table-column>
                            <el-table-column label="状态">
                                <template #default="scope">
                                    <div class="decorate-box">
                                        <div class="decorate" :style="{
                                            background:
                                                scope.row.isSuccess == 1
                                                    ? '#00D679 '
                                                    : scope.row.isSuccess ==
                                                        0
                                                        ? '#FF7E68'
                                                        : ''
                                        }"></div>
                                        <!--  style="color:#1989FA" -->
                                        <p>
                                            {{
                                                scope.row.isSuccess
                                                    ? '成功'
                                                    : '失败'
                                            }}
                                        </p>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作">
                                <template #default="scope">
                                    <div class="operation-box">
                                        <p style="color:#1989FA" class="point" @click="
                                            getInsureDetailAdditionExport(
                                                scope.row.id
                                            )
                                            ">
                                            导出名单
                                        </p>
                                        <text v-if="scope.row.isAllowRevoke && scope.row.managerId != 1"
                                            class="point">/</text>
                                        <!-- v-if="scope.row.isAllowRevoke" -->
                                        <p v-if="scope.row.isAllowRevoke && scope.row.managerId != 1"
                                            style="color:#1989FA" class="point" @click="onLongTermRevoke(scope.row.id)">
                                            撤回</p>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination class="pagination" v-model:currentPage="countPageNum"
                            v-model:page-size="countPageSize" :page-sizes="[10, 30, 50, 100]"
                            layout="total, prev, pager, next, jumper" :total="countTotal"
                            @size-change="getInsureDetailAdditionList" @current-change="getInsureDetailAdditionList">
                        </el-pagination>
                    </div>
                </div>
            </div>
            <div class="block">
                <div class="block-header">
                    <div class="block-title">人员统计</div>
                </div>
                <div class="block-content">
                    <div class="row">
                        <div></div>
                        <tab-capsule class="tab-cap" :active="statisticsTab" :list="['工种', '被派遣单位']"
                            @tabchange="onStatisticsTab" />
                    </div>
                    <div id="echarts"></div>
                </div>
            </div>
        </div>
        <div class="block plan">
            <div class="block-header">
                <div class="block-title">人员名单</div>
                <div class="staff-list">
                    <div class="dressing-by-screening">
                        <el-select v-model="payType" filterable placeholder="筛选状态" class="screen-i"
                            @change="handleCurrentChange">
                            <el-option :label="item" :value="item" v-for="(item, index) in payTypeList"
                                v-bind:key="index">{{
                                    item }}
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <el-date-picker v-model="personneDate" type="date" placeholder="选择日期"
                            @change="getInsureDetailPersonnelList" format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                    </div>
                </div>
            </div>
            <div class="table table-naem">
                <!-- @selection-change="handleSelectionChange" -->
                <el-table :data="personnelList" style="width: 100%" :header-row-style="{ color: '#202536' }"
                    :row-style="{ color: '#5E617D' }" :header-cell-style="{ background: '#F7F8FC' }">
                    <!-- <el-table-column type="index" label="序号" /> -->
                    <el-table-column prop="userName" label="姓名" />
                    <el-table-column label="身份证号">
                        <template #default="scope">
                            <p>
                                {{ scope.row.encryptionIdCardNo }}
                            </p>
                        </template>
                    </el-table-column>
                    <el-table-column label="被派遣单位" prop="serveCompanyName"></el-table-column>
                    <el-table-column width="240px" prop="createTime" label="录入时间" />
                    <el-table-column label="所属工种" prop="occupationName" />
                    <el-table-column label="保险起期" prop="insurStartTime" />
                    <el-table-column label="保险止期" prop="insurEndTime" />
                    <el-table-column label="状态" class="dot" is-dot>
                        <template #default="scoped">
                            <span v-if="scoped.row.policyStatus == '0'" class="rovalsState">
                                <em class="sub" />待生效
                            </span>
                            <span v-if="scoped.row.policyStatus == '1'" class="rovalsState">
                                <em class="adopt" />保障中
                            </span>
                            <span v-if="scoped.row.policyStatus == '2'" class="rovalsState">
                                <em class="stay" />不在保
                            </span>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="pagination" v-model:currentPage="personnelPageNum"
                    v-model:page-size="personnelPageSize" layout="total, prev, pager, next, jumper"
                    :total="personnelTotal" @size-change="getInsureDetailPersonnelList"
                    @current-change="getInsureDetailPersonnelList">
                </el-pagination>
            </div>
        </div>
        <alert-box class="alert-box" data-Title="导出账单" v-if="isExportAllPopup" @close="isExportAllPopup = false">
            <div class="edit-popup-box">
                <div class="row">
                    <div class="name">
                        <span class="important">*</span>
                        格式
                    </div>
                    <div style="width:100%">
                        <el-radio v-model="exportType" label="1" size="large">按天
                        </el-radio>
                        <el-radio v-model="exportType" label="0" size="large">按人员
                        </el-radio>
                    </div>
                </div>
                <div class="row">
                    <div class="name">
                        <span class="important">*</span>
                        选择月份
                    </div>
                    <div style="width:100%">
                        <el-date-picker v-model="exportDate" type="month" placeholder="选择月份" format="YYYY-MM"
                            value-format="YYYY-MM" />
                    </div>
                </div>
                <div class="row-btn">
                    <button class="btn btn-white-blue" @click="isExportAllPopup = false">
                        取消
                    </button>
                    <button class="btn btn-red" style="background:#1989FA" @click="exportWhole">
                        确认导出
                    </button>
                </div>
            </div>
        </alert-box>
    </div>
</template>
<script lang="ts">
import {
    getInsureDetailInfo,
    getInsureDetailAdditionList,
    getInsureDetailPersonnelList,
    getInsureDetailAdditionExport,
    insureDetailAllExport,
    getPlanStatistics,
    PlanStatisticsDto,
    renewalMonthNotify,
    onLongInsuranceRevoke,
    checkStatusPeriod
} from '@/api/long-insure'
import { defineComponent } from 'vue'
import * as echarts from 'echarts'
import AlertBox from '@/components/alert-box.vue'
import tabCapsule from '@/components/tab-capsule.vue'
import { getsaasCompanyinfoapi } from '../api/base'
import { dateFormat, confirm, isWeixin } from '@/utils/util'
import { ElMessageBox, ElMessage } from 'element-plus'
import exportButton from '../components/export-button.vue'
export default defineComponent({
    name: 'LongInsureDetail',
    components: { AlertBox, tabCapsule, exportButton },
    data() {
        return {
            insurCompany: '',
            customerDate: '',
            countDate: '',
            tioInfo: {} as any,
            countPageSize: 5,
            countPageNum: 1,
            countTotal: 0,
            countList: [],
            personnelPageSize: 5,
            personnelPageNum: 1,
            personnelTotal: 100,
            personnelList: [],
            personneDate: '',
            isExportAllPopup: false,
            exportDate: '',
            exportType: '1',
            statisticsData: {} as PlanStatisticsDto,
            statisticsTab: 0,
            canInsureRenewal: false,
            isGoFluctuate: false,
            payTypeList: ['全部', '保障中', '待生效', '不在保'],
            payType: '',
            policyStatusNumber: '' as string | number
        }
    },

    async created() {
        this.customerDate = dateFormat('YYYY-mm', new Date())
        this.getInsureDetailInfo()
        this.getInsureDetailAdditionList()
        this.getInsureDetailPersonnelList()
        // 获取统计数据
        await this.getStatistics()
        this.onStatisticsTab(0)
        this.getRenewalMonthNotify()
    },
    methods: {
        // 长期保近期撤销
        onLongTermRevoke(id: number) {
            console.log(id)
            confirm('', '确定撤回吗？').then(async () => {
                await onLongInsuranceRevoke({
                    id: id,
                    companyPlanId: Number(this.$route.params.id) as number
                })
                await this.getInsureDetailAdditionList()
                this.$message.success('撤回成功')
            })
        },
        onRenew() {
            if (this.isGoFluctuate) {
                this.$message.error('当前时间段不可操作')
                return
            }
            this.$router.push({
                path:
                    '/long-insure-add-subtract/' +
                    'add' +
                    '/' +
                    this.$route.params.id + '/' + 'renewal'
            })
        },
        onInsureAdd() {
            getsaasCompanyinfoapi({ planId: this.$route.params.id }).then(async (res: any) => {
                console.log(res, 'fshgfgydshug')
                if (res.isAreaError && !res.isWhitelist) {
                    ElMessageBox.confirm(
                        '非常抱歉，当前方案不支持该（天津）地区投保，请选择“其他方案”继续投保',
                        '提示',
                        {
                            confirmButtonText: '其他方案',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }
                    )
                        .then(() => {
                            this.$router.back()
                        })
                        .catch(() => {
                            console.log('取消')
                        })
                } else {
                    const result = await checkStatusPeriod()
                    console.log(result, '加保')
                    if (!result.status) {
                        this.$message.error(result.msg)
                        return
                    }
                    this.$router.push({
                        path:
                            '/long-insure-add-subtract/' +
                            'add' +
                            '/' +
                            this.$route.params.id
                    })
                }
            })
        },
        onInsureSubtract() {
            if (this.isGoFluctuate) {
                this.$message.error('当前时间段不可操作')
                return
            }
            this.$router.push({
                path:
                    '/long-insure-add-subtract/' +
                    'reduce' +
                    '/' +
                    this.$route.params.id
            })
        },
        // 基本信息
        async getInsureDetailInfo() {
            const result = await getInsureDetailInfo({
                planId: this.$route.params.id,
                month: this.customerDate
            })
            // result.isEnd = result.endTime ? new Date(result.endTime).getTime() < new Date().getTime() : false

            console.log(result, 'result')
            this.insurCompany = result.insurCompany
            if (result.insurCompany === 'period_002_xdc') {
                const startTime = new Date('2022-09-30 18:00').getTime()
                const endTime = new Date('2022-09-30 24:00').getTime()
                const currentTime = new Date().getTime()
                if ((currentTime > startTime) && (currentTime < endTime)) {
                    this.isGoFluctuate = true
                }
            }
            this.tioInfo = result
        },
        handleCurrentChange(e: string) {
            console.log(e, 'eeeeee标签改变的e是什么')
            this.payType = e
            if (e === '全部') {
                // eslint-disable-next-line no-unused-expressions
                this.policyStatusNumber = ''
            } else if (e === '待生效') {
                // eslint-disable-next-line no-unused-expressions
                this.policyStatusNumber = 0
            } else if (e === '保障中') {
                // eslint-disable-next-line no-unused-expressions
                this.policyStatusNumber = 1
            } else if (e === '不在保') {
                // eslint-disable-next-line no-unused-expressions
                this.policyStatusNumber = 2
            }
            console.log(this.policyStatusNumber, 'policyStatusNumberpolicyStatusNumberpolicyStatusNumberpolicyStatusNumber')
            this.getInsureDetailPersonnelList()
        },
        onStatisticsTab(tab: number) {
            this.statisticsTab = tab
            const element = document.getElementById('echarts') as HTMLElement
            echarts.dispose(element)
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b} <br/>{c}人  ({d}%)'
                },
                series: [
                    {
                        type: 'pie',
                        radius: ['60%', '80%'],

                        label: {
                            position: 'inner',
                            formatter: '{b} {c}人'
                        },
                        data: [] as { value: number; name: string }[]
                    }
                ]
            }
            const charts = echarts.init(element)
            if (tab === 0) {
                option.series[0].data = this.statisticsData.occupationGroup.map(
                    item => ({
                        value: item.count,
                        name: item.occupationName
                    })
                )
            } else {
                option.series[0].data = this.statisticsData.serveCompanyGroup.map(
                    item => ({
                        value: item.count,
                        name: item.serveCompanyName
                    })
                )
            }
            charts.setOption(option)
        },
        async getStatistics() {
            this.statisticsData = await getPlanStatistics({
                companyPlanId: this.$route.params.id as string,
                policyStatus: ''
            })
        },
        // 加减记录列表
        async getInsureDetailAdditionList() {
            const result = await getInsureDetailAdditionList({
                pageSize: this.countPageSize,
                pageNum: this.countPageNum,
                companyPlanId: this.$route.params.id,
                insurStartDate: this.countDate
            })
            this.countList = result.list
            this.countTotal = result.total
        },
        // 改变加减保 每页条数
        countSizeChange() {
            console.log(this.countPageSize, 'countPageSize')
        },
        // 人员列表
        async getInsureDetailPersonnelList() {
            const result = await getInsureDetailPersonnelList({
                pageSize: this.personnelPageSize,
                pageNum: this.personnelPageNum,
                companyPlanId: this.$route.params.id,
                insurStartTime: this.personneDate,
                policyStatus: this.policyStatusNumber
            })
            result.list.map((item: any) => {
                item.encryptionIdCardNo = item.idCardNo.replace(
                    /(.{3})(?:\d+)(.{4})$/,
                    '$1*********$2'
                )
            })
            this.personnelList = result.list
            this.personnelTotal = result.total
        },
        // 导出加减保单条数据
        async getInsureDetailAdditionExport(id: string) {
            const result = await getInsureDetailAdditionExport({ id })
            console.log(result, 'result')
            window.location.href =
                process.env.VUE_APP_BASE_URL +
                '/common/download?delete=true&fileName=' +
                result

            this.$message.success('导出成功！')
        },
        // 按天或按人导出
        async exportWhole() {
            console.log('导出')
            const result = await insureDetailAllExport({
                queryMonth: this.exportDate,
                queryType: this.exportType,
                companyPlanId: this.$route.params.id
            })
            window.location.href =
                process.env.VUE_APP_BASE_URL +
                '/common/download?delete=true&fileName=' +
                result
            this.$message.success('导出成功！')
            this.isExportAllPopup = false
        },
        async getRenewalMonthNotify() {
            const result = await renewalMonthNotify({
                planId: this.$route.params.id
            })
            this.canInsureRenewal = result.canInsureRenewal
            console.log(result, 'result月检测')
        },
        handleExport() {
            this.isExportAllPopup = true
        }
    }
})
</script>
<style lang="stylus" scoped>
.header.block
  padding 24px
  margin-top 20px
  display flex
  align-items center
  justify-content space-between

  .header-left
    display flex
    align-items center

  .portrait
    width 72px
    height 72px
    border-radius 50%
    margin-right 24px

  .left-info-title
    font-weight 600
    color #202536
    font-size 20px
    display flex
    align-items center

  .info-title-tips
    font-size 12px
    margin-left 9px
    padding 3px 8px
    background #FFF2EF
    color #FF7E68

  .info-title-month
    margin-left 9px

  .left-info-date
    font-size 12px
    color #5E617D

.container-info-box
  background #ffffff
  padding 0px 0px 16px 0
  border-radius 8px
  border: 1px solid #e8e9ea;
  margin-top 16px

  .container-row-box
    padding 16px

  .block-active-list {
    display flex
    align-items center
    justify-content center
  }

  .block-active
    margin 0 8px 0 8px
    background #F7F8FC
    border none

.container-list
  display grid
  grid-template-columns repeat(3, 1fr)
  grid-gap 16px
  margin-top 16px

.block
  padding 0
  width: 100%
  margin-top 0

.block-header
  space-between(false)
  border-bottom 1px solid #ffffff
  padding 14px 16px 8px

.block-title
  font-size font-small
  color black
  font-weight bold

.block-more
  display flex
  align-items center
  color color-blue

  .triangle
    margin-left 8px
    border-color color-blue transparent transparent transparent
    transform rotate(270deg)
    top 0

.block-content
  // space-between()
  padding 18px 16px

.premium-trend
  grid-column-end span 2

.plan
  margin-top 20px
  grid-column-end span 3

.key
  font-size font-mini
  margin-bottom: 6px

.balance
  font-style italic

.number
  font-weight bold
  font-size font-large

.img-chart
  width 158px
  height 37px

.recharge-btn
  border-radius: 100px
  margin 16px 0 0
  height 28px

.nav
  padding 24px
  margin-top 8px

.nav-item
  text-align center
  font-size font-mini

  img
    margin-bottom 8px

.plan-list
  display grid
  grid-template-columns repeat(auto-fill, 264px)
  grid-gap 16px

.plan-item
  width 100%
  height: 183px;
  background-size 100% 100%

.plan-add
  background-color #F7F8FC
  border-radius 8px

.btn
  margin-left 20px
  width 90px

.table-naem
  padding 16px 24px

.operation-type-box
  width 72px
  height 30px
  background #EBFFF8
  border-radius 15px
  display flex
  align-items center
  justify-content center

  .operation-type-img
    width 16px
    height 16px
    margin-right 3px

.operation-type-box-active
  background #FFF1F0

.pagination
  text-align right
  margin-top 20px

.decorate-box
  display flex
  align-items center

.decorate
  width 6px
  height 6px
  border-radius 50%
  margin-right 5px

.edit-popup-box
  padding 24px 50px

  .row-btn
    display flex
    align-items center
    justify-content center
    margin-top 60px

  .row
    margin-bottom 20px

  .name
    width 200px
    font-weight 600
    font-size 16px

.header-right
  display flex

  .right-btn
    display flex
    align-items center
    justify-content center

  .header-right-img
    margin-right 6px
    width 20px
    height 20px

/deep/ .alert-box .container-c
  width 470px

.rovalsState em {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  width: 6px;
  height: 6px;
  border-radius: 3px;
  margin-right: 5px;
}

.rovalsState em.sub {
  background: #1989FA;
}

.rovalsState em.adopt {
  background: #00a854;
}

.rovalsState em.stay {
  background: #FF7E68;
}

#echarts
  width 600px
  height 300px
  margin-top 50px

/deep/ .tab-cap .tab
  width 90px

.staff-list
  display flex;
  align-items center;

  .dressing-by-screening
    margin-right 16px;
    width 100px;

    .screen-i
      font-size 20px;

  .dressing-by-screening ::v-deep .el-input__inner
    padding-right 27px;
.operation-box
	display flex;
	align-items center;
</style>
